#include "socket_listening.h"

#include <cstring> /* NULL */

#ifdef VXWORKS
# include <selectLib.h>
#endif

eSocket*
eListeningSocket::accept (void)
{
  eSocketAddress address;

  int new_sock_handle;
  
#if defined (VXWORKS) || defined (_WIN32)
  new_sock_handle = ::accept (handle_, (sockaddr *)&address.address, (int *)&address.size);
#else
  new_sock_handle = ::accept (handle_, (sockaddr *)&address.address, &address.size);
#endif

  if (new_sock_handle >= 0) {
    eSocket* socket = new eSocket (new_sock_handle, address);
    return socket;
  }

  return NULL;
}

bool
eListeningSocket::listen (int backlog)
{
  if (::listen (handle_, backlog) != -1)
    return true;

  return false;
}

/**
 * Returns true when there is data waiting for this socket,
 *   blocks for at most msecs-many milliseconds.
 *
**/
bool
eListeningSocket::select (int msecs)
{
  struct timeval timeout;

  timeout.tv_sec  = 0;
  timeout.tv_usec = 1000 * msecs;

  FD_ZERO (&fds_);
  FD_SET  (handle_, &fds_);

  if (::select (handle_ + 1, &fds_, NULL, NULL, &timeout) > 0)
    return true;

  return false;
}
